﻿using ApplicationManager.Model;
using DingGC.Library.Cache;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ApplicationManager.Services
{
    public class AppService
    {
        private string key = "apps";
        private readonly ICache<RocksCache> cache;

        public AppService(ICache<RocksCache> cache)
        {
            this.cache = cache;
        }

        /// <summary>
        /// 启动进程
        /// </summary>
        /// <param name="appInfo"></param>
        /// <returns></returns>
        public async Task<bool> Create(AppInfoModel appInfo)
        {
            try
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = appInfo.App,
                        Arguments = appInfo.Args,
                        RedirectStandardOutput = true,
                        UseShellExecute = false,
                        CreateNoWindow = true
                    }
                };

                process.Start();
                Thread.Sleep(500);
                appInfo.ProcessId = process.Id;
                appInfo.Status = GetAppStatus(appInfo.ProcessId);


                List<AppInfoModel> appInfoModels = GetAppInfos();

                appInfoModels.Add(appInfo);
                SaveAppInfo(appInfoModels);
                return appInfo.Status;

            }
            catch (System.Exception ex)
            {
                return false;
               
            }
            // 启动应用程序  
          
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> Start(string id)
        {
            List<AppInfoModel> appInfoModels = GetAppInfos();
            var appInfo = appInfoModels.Where(p => p.Id == id).FirstOrDefault();

            // 启动应用程序  
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = appInfo.App,
                    Arguments = appInfo.Args,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };

            process.Start();
            Thread.Sleep(500);
            appInfo.ProcessId = process.Id;
            appInfo.Status = GetAppStatus(appInfo.ProcessId);


            

           // appInfoModels.Add(appInfo);
            SaveAppInfo(appInfoModels);
            return appInfo.Status;
        }

        /// <summary>
        /// Stop app
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> Stop(string id)
        {
            var appInfos = GetAppInfos();
            AppInfoModel appInfo = appInfos.FirstOrDefault(p => p.Id == id);
            if (appInfo == null)
                return false;
            KillApp(appInfo.ProcessId);
            appInfo.Status = false;
            SaveAppInfo(appInfos);
            return true;
        }
        /// <summary>
        /// 删除进程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> Delete(string id)
        {
            var appInfos = GetAppInfos();
            if (appInfos == null || appInfos.Count == 0)
                return false;
            AppInfoModel appInfo = appInfos.FirstOrDefault(p => p.Id == id);
            if (appInfo == null)
                return false;
            KillApp(appInfo.ProcessId);
            appInfo.Status = false;
            appInfos.Remove(appInfo);
            SaveAppInfo(appInfos);
            return true;
        }


        /// <summary>
        /// 返回进程状态
        /// </summary>
        /// <returns></returns>
        public async Task<List<AppInfoModel>> GetAppStatus()
        {
            var appInfos = GetAppInfos();
            foreach (var appInfo in appInfos)
            {
                appInfo.Status = GetAppStatus(appInfo.ProcessId);
            }
            return appInfos;
        }

        private List<AppInfoModel> GetAppInfos()
        {
            List<AppInfoModel> list = null;
            if (cache.Exists(key))
            {
                list = cache.Get<List<AppInfoModel>>(key);
                return list;
            }
            list = new List<AppInfoModel>();
            return list;
        }

        private AppInfoModel GetAppInfo(string id)
        {
            if (cache.Exists(key))
            {
                var list = cache.Get<List<AppInfoModel>>(key);
                var appinfo = list.FirstOrDefault(p => p.Id == id);
                return appinfo;

            }

            return null;
        }
        /// <summary>
        /// 获取进程状态
        /// </summary>
        /// <param name="processid"></param>
        /// <returns></returns>
        private bool GetAppStatus(int processid)
        {
            var processes = Process.GetProcesses(); // 获取所有当前运行的进程  
            var process = processes.FirstOrDefault(p => p.Id == processid);
            if (process != null)
            {
              return true;

            }
            return false;
        }

        /// <summary>
        /// 杀死进程
        /// </summary>
        /// <param name="processid"></param>
        /// <returns></returns>
        private bool KillApp(int processid)
        {
            var processes = Process.GetProcesses(); // 获取所有当前运行的进程  
            var process = processes.FirstOrDefault(p => p.Id == processid);
            if (process != null)
            {
                process.Kill();

            }
            return true;
            
        }


        private bool SaveAppInfo(List<AppInfoModel> appInfos)
        {
            cache.Set(key, appInfos);
            return true;
        }
    }
}
